<script setup>
import { map, omit } from 'lodash-es';
import { useRequest, useWatch, useDownload } from '@/hooks';
import { useSelectIns } from '@/store/zdwh.js';
import { getTreeData, getDeviceSysTree, getMeterList, unbindMeter } from '@/api/index.js';
import { Message, MessageBox } from 'element-ui';
import { TableList } from '@/components/MainComponents.js';
import ToolTip from '@/components/ToolTip/index.vue';
import DialogTopoImport from './DialogTopoImport.vue';
import DialogMeterBind from './DialogMeterBind.vue';

const selectInsStore = useSelectIns();
const dialogTopoImport = ref(null);
const dialogMeterBind = ref(null);
const treeData = ref(null);
const activeName = ref('building');
const topoTree = ref(null);
const treeParams = ref({ enterpriseCode: selectInsStore.selectIns?.enterpriseCode });
const defaultProps = { children: 'children', label: 'name' };
const queryData = ref({
  enterpriseCode: null,
  buildingCode: null,
  dsCode: null,
  enterpriseFlag: false,
  pageNum: 1,
  pageSize: 10,
});

const deviceCodes = ref([]);

const unbindParams = computed(() => ({
  ...omit(queryData.value, ['pageNum', 'pageSize']),
  deviceCodes: deviceCodes.value,
}));
const tableBoxRef = ref(null);
const tableHeight = ref(null);
const handleUnbind = row => {
  MessageBox.confirm('是否确认解绑', '提示', {
    confirmButtonText: '是',
    cancelButtonText: '否',
    type: 'warning',
  }).then(() => {
    deviceCodes.value = [row.deviceCode];
    runUnbind(unbindParams.value);
  });
};
const columnObj = {
  selection: true,
  index: true,
  fixed: true,
  columnData: [
    {
      text: true,
      prop: 'deviceViewId',
      label: '计量表编号',
      width: '120px',
    },
    {
      text: true,
      prop: 'deviceName',
      label: '计量表名称',
      width: '120px',
    },
    {
      text: true,
      prop: 'deviceTypeName',
      label: '计量表类型',
      width: '120px',
    },
    {
      text: true,
      prop: 'position',
      label: '计量表安装位置',
      width: '150px',
    },
    {
      text: true,
      prop: 'energyType',
      label: '计量能源类型',
      width: '110px',
    },
    {
      text: true,
      prop: 'energyUnit',
      label: '计量单位',
      width: '90px',
    },
    {
      slotName: 'bindTime',
      label: '绑定时间',
      width: '120px',
    },
    {
      label: '操作',
      width: '80px',
      operations: [
        {
          type: 'text',
          label: '解绑',
          buttonClick: handleUnbind,
        },
      ],
    },
  ],
};
const getNodeID = () => {
  return { building: 'buildingCode', deviceSys: 'dsCode' }[activeName.value];
};
const getBindTime = () => {
  return { building: 'buildingBindTime', deviceSys: 'dsBindTime' }[activeName.value];
};

const handleClick = () => {
  runTreeEnum[activeName.value](treeParams.value);
};
const handleImport = () => {
  dialogTopoImport.value.visible = true;
};
const handleDownload = () => {
  const downloadUrl = {
    building: '/energyservice/device/topology/templateDownload/building',
    deviceSys: '/energyservice/device/topology/templateDownload/ds',
  };
  useDownload(downloadUrl[activeName.value], {});
};
const handleNodeClick = (data, node) => {
  resetQuery();
  if (node.level === 1 && activeName.value == 'building') {
    queryData.value.enterpriseFlag = true;
  } else {
    queryData.value.enterpriseFlag = false;
    queryData.value[getNodeID()] = data.id;
  }
  runTable(queryData.value);
};
const handleBind = () => {
  dialogMeterBind.value.visible = true;
};
const batchUnbind = () => {
  if (deviceCodes.value.length > 0) {
    MessageBox.confirm('是否确认批量解绑', '提示', {
      confirmButtonText: '是',
      cancelButtonText: '否',
      type: 'warning',
    }).then(() => {
      runUnbind(unbindParams.value);
    });
  } else {
    Message.warning('请选择需要解绑的计量表');
  }
};
const handleSuccess = bool => {
  if (bool) {
    runTable(queryData.value);
  }
};
const getList = e => {
  queryData.value.pageNum = e.page;
  queryData.value.pageSize = e.limit;
  runTable(queryData.value);
};
const handleSelectionChange = val => {
  deviceCodes.value = map(val, v => v.deviceCode);
};
const resetQuery = () => {
  queryData.value.buildingCode = null;
  queryData.value.dsCode = null;
  queryData.value.pageNum = 1;
  queryData.value.pageSize = 10;
};

const [, bLoading, runBldTree] = useRequest(getTreeData, {
  manual: true,
  onSuccess: res => {
    treeData.value = [
      {
        id: selectInsStore.selectIns?.enterpriseCode ?? null,
        name: selectInsStore.selectIns?.enterpriseName ?? null,
        children: res.data ?? [],
      },
    ];
    queryData.value.enterpriseFlag = true;
    resetQuery();
    runTable(queryData.value);
    nextTick(() => {
      topoTree.value.setCurrentKey(treeData.value[0]?.id);
    });
  },
});
const [, dsLoading, runDSTree] = useRequest(getDeviceSysTree, {
  manual: true,
  onSuccess: res => {
    treeData.value = res.data ?? [];
    resetQuery();
    queryData.value.enterpriseFlag = false;
    queryData.value.dsCode = treeData.value?.[0]?.id;
    runTable(queryData.value);
    nextTick(() => {
      topoTree.value.setCurrentKey(treeData.value[0]?.id);
    });
  },
});

const [res, tLoading, runTable] = useRequest(getMeterList, { manual: true });
const [, , runUnbind] = useRequest(unbindMeter, {
  manual: true,
  onSuccess: res => {
    if (res.code === 200) {
      Message.success(res.msg);
      runTable(queryData.value);
    }
  },
});
const runTreeEnum = {
  building: runBldTree,
  deviceSys: runDSTree,
};

onMounted(() => {
  nextTick(() => {
    tableHeight.value = tableBoxRef.value.clientHeight - 183;
  });
});
useWatch(
  () => selectInsStore.selectIns,
  n => {
    if (n?.enterpriseCode) {
      treeParams.value.enterpriseCode = n.enterpriseCode;
      queryData.value.enterpriseCode = n.enterpriseCode;
      runTreeEnum[activeName.value](treeParams.value);
    }
  },
  { deep: true, immediate: true },
);
</script>

<template>
  <ul class="u-w100 u-h100 u-df-spb DeviceSystTree-wrapper">
    <li class="u-pt7 u-pb20 u-mr20 u-base-fg">
      <el-tabs class="u-base-fg" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="建筑树结构" name="building"></el-tab-pane>
        <el-tab-pane label="设备系统结构" name="deviceSys"></el-tab-pane>
      </el-tabs>
      <div class="u-mt20 u-pl20 u-mb20">
        <el-button type="primary" size="small" plain @click="handleImport">导入表计拓扑</el-button>
        <el-button type="primary" size="small" plain @click="handleDownload">下载模板</el-button>
      </div>
      <el-tree
        ref="topoTree"
        v-loading="bLoading || dsLoading"
        :data="treeData ?? []"
        :props="defaultProps"
        :highlight-current="true"
        :current-node-key="treeData?.[0]?.id ?? null"
        :expand-on-click-node="false"
        node-key="id"
        default-expand-all
        class="u-pl20"
        style="height: calc(100% - 111px); overflow-y: auto"
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node u-fs14" slot-scope="{ node, data }">
          <ToolTip class="tree-lable u-pr20" :content="data.name" effect="dark" />
        </span>
      </el-tree>
    </li>
    <li ref="tableBoxRef" class="u-f1 u-p20 u-base-fg">
      <div class="u-prim-text u-fs20">计量表信息</div>
      <div class="u-df-ed u-mt20 u-mb20">
        <el-button type="primary" size="small" plain @click="handleBind">绑定计量表</el-button>
        <el-button type="primary" size="small" plain @click="batchUnbind">批量解绑</el-button>
      </div>
      <TableList
        v-loading="tLoading"
        :tableData="res?.rows ?? []"
        :columObj="columnObj"
        :pageObj="queryData"
        :total="res?.total ?? 0"
        :height="tableHeight"
        width="100%"
        @getList="getList"
        @handleSelectionChange="handleSelectionChange"
      >
        <template v-slot:bindTime="{ scope }">
          {{ queryData.enterpriseFlag ? scope.row?.enterpriseBindTime ?? '--' : scope.row?.[getBindTime()] ?? '--' }}
        </template>
      </TableList>
    </li>
    <DialogTopoImport ref="dialogTopoImport" :activeName="activeName" @success="handleSuccess" />
    <DialogMeterBind ref="dialogMeterBind" :queryParams="queryData" @success="handleSuccess" />
  </ul>
</template>

<style lang="scss" scoped>
.DeviceSystTree-wrapper {
  > li {
    height: 100%;
  }
  > li:first-of-type {
    width: 30%;
    max-width: 30%;
    overflow-x: auto;
  }
}
.u-pt7 {
  padding-top: 7px;
}
.u-f1 {
  flex: 1;
}
</style>
